package com.keiou.drink;

import android.app.Application;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.keiou.drink.api.AbsSubscriber;
import com.keiou.drink.api.exception.ApiException;
import com.keiou.drink.api.remote.Api;
import com.keiou.drink.api.rx.RxHelper;
import com.keiou.drink.response.VoiceStatusRes;
import com.keiou.drink.response.base.HttpResult;
import com.keiou.drink.util.FakeCrashUtil;
import com.keiou.drink.util.MediaHelper;
import com.keiou.drink.util.PrefsHelper;
import com.keiou.drink.util.TLog;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import rx.Subscription;
import timber.log.Timber;

/**
 * 作者 ：Bob on 2017/7/31.
 * 邮箱 ：motherlovefather@126.com
 */

public class AppContext extends Application {

    private static AppContext instance;


    private RefWatcher refWatcher;

    private Handler handler = new Handler();

    private Subscription subscription;

    public static final int DELAYMILLIS = 2000;
    public static final int DELAYPAYMILLIS = 5000;

    private String deviceId;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        deviceId = PrefsHelper.gePreDeviceId(this);
        initlog();
        initGlide();
        initDetection();
        delayLoadData(DELAYMILLIS);
    }

    public static AppContext getInstance() {
        return instance;
    }

    /**
     * log初始化
     */
    private void initlog() {
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        } else {
            Timber.plant(new CrashReportingTree());
        }
    }

    private void initGlide() {
        Glide.get(this).register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(new OkHttpClient()));
    }


    /**
     * 内存检测
     */
    private void initDetection() {
        refWatcher = LeakCanary.install(this);
    }

    public static RefWatcher getRefWatcher() {
        return getInstance().refWatcher;
    }

    private static class CrashReportingTree extends Timber.Tree {
        @Override
        protected void log(int priority, String tag, String message, Throwable t) {
            if (priority == Log.VERBOSE || priority == Log.DEBUG) {
                return;
            }
            FakeCrashUtil.log(priority, tag, message);
            if (t != null) {
                if (priority == Log.ERROR) {
                    FakeCrashUtil.logError(t);
                } else if (priority == Log.WARN) {
                    FakeCrashUtil.logWarning(t);
                }
            }
        }
    }

    public Map<String, String> getRequestHeader() {
        Map<String, String> map = new HashMap<>();
        map.put("Access-Token", "Tolen");
        return map;
    }

    private void delayLoadData(int delayMillis) {
        TLog.d("delayLoadData");
        if (TextUtils.isEmpty(deviceId)) {//没获取到权限
            deviceId = PrefsHelper.gePreDeviceId(this);
            handler.postDelayed(() -> delayLoadData(delayMillis), 30 * 1000);
        } else {
            handler.postDelayed(() -> loadStatus(), delayMillis);
        }


    }


    private void loadStatus() {
        subscription = Api.getInstance().getVoiceStatus(PrefsHelper.getDeviceId(this))
                .compose(RxHelper.applySchedulers())
                .subscribe(new AbsSubscriber<HttpResult<VoiceStatusRes>>() {
                    @Override
                    public void onNext(HttpResult<VoiceStatusRes> result) {
//语音状态(1：正常，2：为了您的安全请不要遮挡光栅 3:饮料制作完成，请领取 4:在左下方取杯盖）
                        VoiceStatusRes voiceStatusRes = result.getResult();
                        String status = voiceStatusRes.getStatus();
                        if ("2".equals(status)) {
                            playMedia(2);
                            delayLoadData(DELAYPAYMILLIS);
                        } else if ("3".equals(status)) {
                            playMedia(3);
                            delayLoadData(DELAYPAYMILLIS);
                        } else if ("4".equals(status)) {
                            playMedia(4);
                            delayLoadData(DELAYPAYMILLIS);
                        } else {
                            delayLoadData(DELAYMILLIS);
                        }

                    }


                    @Override
                    protected void onError(ApiException ex) {
                        delayLoadData(DELAYMILLIS);
                    }

                    @Override
                    protected void onIntercept(int code) {

                    }
                });
    }


    /**
     * 播放音乐
     * @param status
     */
    public void playMedia(int status){
        switch (status){
            case 1:
                MediaHelper.getInstance().play(AppContext.this, R.raw.status_1);
                break;
            case 2:
                MediaHelper.getInstance().play(AppContext.this, R.raw.status_2);
                break;
            case 3:
                MediaHelper.getInstance().play(AppContext.this, R.raw.status_3);
                break;
            case 4:
                MediaHelper.getInstance().play(AppContext.this, R.raw.status_4);
                break;
        }

    }


    @Override
    public void onTerminate() {
        unsubscribe();
        super.onTerminate();
    }

    private void unsubscribe() {
        if (null != subscription && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }


}
